package com.newlink.building.common_base.activities

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.view.View
import androidx.core.content.FileProvider
import com.newlink.building.common_base.R
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.base.NL_OnActivityCallback
import com.newlink.building.common_base.ext.getBoolean
import com.newlink.building.common_base.ext.getSerializable
import com.newlink.building.common_base.utils.NLog
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


/**
 * @Author: Jake
 * @Date: 2023-03-31
 * @Description: 相机跳转类
 */
class NL_CameraActivityNL : NL_BaseActivity() {

    companion object {

        const val INTENT_KEY_IN_FILE: String = "file"
        const val INTENT_KEY_IN_VIDEO: String = "video"
        const val INTENT_KEY_OUT_ERROR: String = "error"
        const val IMG_PATH: String = "/neutral_img"
        const val IMG_SUFFIX: String = ".jpg"

        fun start(activity: NL_BaseActivity, listener: OnCameraListener?) {
            start(activity, false, listener)
        }

        fun start(activity: NL_BaseActivity, video: Boolean, listener: OnCameraListener?) {
            val file: File = createCameraFile2(video)
            NLog.d("[创建图片文件] -------> ${file.absolutePath}")
            val intent = Intent(activity, NL_CameraActivityNL::class.java)
            intent.putExtra(INTENT_KEY_IN_FILE, file)
            intent.putExtra(INTENT_KEY_IN_VIDEO, video)
            activity.startActivityForResult(intent, object : NL_OnActivityCallback {

                override fun onActivityResult(resultCode: Int, data: Intent?) {

                    if (listener == null) {
                        return
                    }
                    when (resultCode) {
                        RESULT_OK -> {
                            if (file.isFile) {
                                NLog.d("相机拍照回调::onSelected: $file")
                                listener.onSelected(file)
                            } else {
                                listener.onCancel()
                            }
                        }

                        RESULT_ERROR -> {
                            var details: String? = null
                            if (data != null) {
                                details = data.getStringExtra(INTENT_KEY_OUT_ERROR)
                            }
                            if (details == null) {
                                details = activity.getString(R.string.common_unknown_error)
                            }
                            listener.onError(details)
                        }

                        else -> listener.onCancel()
                    }
                }
            })
        }

        fun getImgDirectory(context: Context): String {
//            return if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
//                Environment.getExternalStorageDirectory().absolutePath + IMG_PATH
//            else  Environment.getDataDirectory().absolutePath + IMG_PATH

            return context.getExternalFilesDir("door")?.absolutePath!!

        }

        fun getImagePath(context: Context): String {
            val file = File(getImgDirectory(context));
            if (!file.exists()) {
                file.parentFile?.mkdirs(); // getParentFile()
                //注意此处创建文件调用getParentFile()再调用    mkdirs()
            }
            return getImgDirectory(context)
//            return getImgDIrectory() + imgName + IMG_SUFFIX;
//              return File(getImgDIrectory() + imgName + IMG_SUFFIX)
        }

        private fun createCameraFile(context: Context, video: Boolean): File {
            return File(
                getImagePath(context), ((if (video) "VID" else "IMG") + "_" +
                        SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) +
                        (if (video) ".mp4" else ".jpg"))
            )
        }

        /**
         * 创建一个拍照图片文件路径
         */
        private fun createCameraFile2(video: Boolean): File {
            var folder = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                "Camera"
            )
            if (!folder.exists() || !folder.isDirectory) {
                if (!folder.mkdirs()) {
                    folder = Environment.getExternalStorageDirectory()
                }
            }
            return File(
                folder, ((if (video) "VID" else "IMG") + "_" +
                        SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) +
                        (if (video) ".mp4" else ".jpg"))
            )
        }
    }

    override fun attachLayoutRes(): View {
        return View(this)
    }

    override fun initView() {}

    @SuppressLint("QueryPermissionsNeeded")
    override fun initData() {
        val intent = Intent()
        if (intent.getBoolean(INTENT_KEY_IN_VIDEO)) {
            intent.action = MediaStore.ACTION_VIDEO_CAPTURE
        } else {
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
        }
        val componentVal = intent.resolveActivity(packageManager)
        if (componentVal == null) {
            setResult(
                RESULT_ERROR,
                Intent().putExtra(INTENT_KEY_OUT_ERROR, getString(R.string.camera_launch_fail))
            )
            finish()
            return
        }
        val file: File? = intent.getSerializable(INTENT_KEY_IN_FILE)
        if (file == null) {
            setResult(
                RESULT_ERROR,
                Intent().putExtra(INTENT_KEY_OUT_ERROR, getString(R.string.camera_image_error))
            )
            finish()
            return
        }
        val imageUri: Uri? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 通过 FileProvider 创建一个 Content 类型的 Uri 文件
            FileProvider.getUriForFile(this, "$packageName.fileprovider", file)
        } else {
            Uri.fromFile(file)
        }

        NLog.e("[imageUri设定] --> $imageUri")
        // 对目标应用临时授权该 Uri 所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        // 将拍取的照片保存到指定 Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)

        startActivityForResult(intent, object : NL_OnActivityCallback {
            override fun onActivityResult(resultCode: Int, data: Intent?) {

                if (resultCode == RESULT_OK) {
                    NLog.e("拍照确认完毕 -> ${file.path}")
                    // 通知系统多媒体扫描该文件，否则会导致拍摄出来的图片或者视频没有及时显示到相册中，而需要通过重启手机才能看到
                    MediaScannerConnection.scanFile(
                        applicationContext,
                        arrayOf(file.path),
                        null,
                        null
                    )
                }
                setResult(resultCode)
                finish()
            }
        })
    }


    /**
     * 拍照选择监听
     */
    interface OnCameraListener {

        fun onSelected(file: File)

        fun onError(details: String)

        fun onCancel() {}
    }
}